<?php
// +--
// | https://github.com/haojohnny
// | @Author: Johnny
// | Date: 2019-07-04 19:12
// | Remark:
// |

namespace wuwu\cosydevtool\command\make;

use think\console\Input;
use think\console\Input\Argument;
use think\console\Output;
use think\facade\Db;
use wuwu\cosydevtool\BaseMake;

class Model extends BaseMake
{
    protected $type = 'model';

    public function configure()
    {
        $this->setName('cosy:model')
            ->addArgument('name', Argument::REQUIRED, 'Please input your class name')
            ->addArgument('tableName', Argument::REQUIRED, 'Please input your table name')
            ->setDescription('创建一个model模型');
    }

    protected function execute(Input $input, Output $output)
    {
        $this->executeBuild($input, $output);
    }

    // 填充模板
    public function buildClass($name)
    {
        $stub = $this->getStub();
        $namespace = trim(implode('\\', array_slice(explode('\\', $name), 0, -1)), '\\');

        $class = str_replace($namespace . '\\', '', $name);

        $modelName = $class.'Model';

        $tableName = $this->input->getArgument('tableName');
        $res = Db::query("show full COLUMNS FROM $tableName");
        foreach ($res as $key => $val){
            if($val['Extra'] == 'auto_increment'){
                $pk = $val['Field'];
                break;
            }
        }
        $prefix_num = strlen(config('database.connections.mysql.prefix'));
        $tableName = substr($tableName,$prefix_num);


        $search = [
            '{%createTime%}',
            '{%className%}',
            '{%namespace%}',
            '{%tableName%}',
            '{%pk%}',
            '{%modelName%}'
        ];

        $replace = [
            date('Y-m-d H:i'),
            $class,
            $namespace,
            $tableName,
            $pk,
            $modelName
        ];

        return str_replace($search, $replace, $stub);
    }

    /**
     * 获取模板
     * @return string
     */
    protected function getStub()
    {
        $path = __DIR__.DIRECTORY_SEPARATOR.'stubs'.DIRECTORY_SEPARATOR.$this->type.'.stub';
        return file_get_contents($path);
    }

    protected function getPathName(string $name): string
    {
        $name = str_replace('app\\', '', $name);
       
        $name = $name.'Model';
        
        return $this->app->getBasePath() . ltrim(str_replace('\\', '/', $name), '/') . '.php';
    }
}